package cn.itcast.mq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


/**
 * 当有消息发送失败时，会将消息传到该交换机和队列当中了。
 * 所以要：
 * 1. 创建交换机
 * 2. 创建队列
 * 3. 绑定交换机和队列 并且指定路由key
 *
 * 4. 覆盖spring默认的Bean，指定自己的策略：
 * RepublishMessageRecoverer
 */
//@Component
public class ErrorMessageConfig {

    @Bean
    public DirectExchange errorMessageExchange(){
        return new DirectExchange("error.direct");
    }
    @Bean
    public Queue errorQueue(){
        return  new Queue("error.queue",true);
    }
    // 绑定：
    @Bean
    public Binding errorBingding(DirectExchange errorMessageExchange,Queue errorQueue){
        return  BindingBuilder.bind(errorQueue).to(errorMessageExchange).with("error");
    }

    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate,"error.direct","error");
    }

}
